package com.tobdev.qywxinner.utils;

import com.tobdev.qywxinner.model.entity.QywxInnerUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class JWTUtils {

    private static final long EXPIRE = 60000 * 60 * 24 * 7;

    @Value("${jwt.secret}")
    private String secret;

    private static final String TOKEN_PREFIX = "tobdev";

    private static final String SUBJECT = "tobdev";

    public String geneJsonWebToken(QywxInnerUser user) {
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("uid", user.getId())
                .claim("user_id", user.getUserId())
                .claim("user_name", user.getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, secret).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    public Claims checkJWT(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
        } catch (Exception e) {
            log.error("claims 解析错误", e);
            return null;
        }
    }

}
